package com.sbio.udiapp.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

    // 压缩多个日志文件为 ZIP 文件
    public static File compressLogsToZip(List<File> logFiles, String zipFileName) throws IOException {
        File zipFile = new File(zipFileName);

        // 创建输出流
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zipOut = new ZipOutputStream(fos);

        // 压缩每个日志文件
        for (File logFile : logFiles) {
            if (logFile.isFile()) {
                FileInputStream fis = new FileInputStream(logFile);
                BufferedInputStream bis = new BufferedInputStream(fis);

                // 将日志文件添加到 ZIP 文件中
                ZipEntry zipEntry = new ZipEntry(logFile.getName());
                zipOut.putNextEntry(zipEntry);

                // 写入文件数据
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = bis.read(buffer)) != -1) {
                    zipOut.write(buffer, 0, bytesRead);
                }

                // 关闭输入流
                bis.close();
                fis.close();
            }
        }

        // 关闭输出流
        zipOut.close();
        fos.close();

        return zipFile;
    }
}
